import React from "react";
import {inject, observer} from 'mobx-react';
import {Tools, List, InputItem, Toast, Bubble, Button, Flex} from "weaver-mobile";
import {getAuthData} from "../../apis/caauthapis";
import {transQueryParams} from "../../util/common";
import {checkCAAuth, getCAAuthInfo, suppoertCAAuth} from "../../../workflowpublic/util/CAJsApi";
import {saveCAAuthResult} from "../../../workflowpublic/apis/secondAuth";
import * as EmSDK from '../../util/emSDK';

const getLabel = Tools.getLabel;

export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentWillMount() {
        const {location} = this.props;
        const queryParams = transQueryParams(location) || {};
        const {authKey} = queryParams;
        getAuthData(queryParams).then(data => {
            const {success} = data;
            if (success == 1) {
                const authData = data.data;
                this.setState({success, authKey, ...authData});
                this.getCACert();
            } else {
                const {message} = data;
                Toast.fail(message, 0);
                this.setState({success});
            }
        });


        //设置EM客户端顶部头信息
        EmSDK.doInitEmSDK();
        EmSDK.controlEmTopNav({title: getLabel(501216, "CA证书验证")});
    }


    getCACert() {
        if (suppoertCAAuth()) {
            getCAAuthInfo(data => this.setCAAuthInfo(data));
        } else {
            const errorMsg = getLabel(501212, "您当前的客户端不支持CA认证", 0);
            Toast.fail(errorMsg, 0);
        }
    }

    setCAAuthInfo(data) {
        const errCode = data.errCode;
        const errMsg = data.errMsg;
        const caCertInfo = data.getCACertInfo;

        if (errCode == 0) {       //成功
            if (caCertInfo) {
                const state = this.state;
                this.setState({...state, ...caCertInfo});
            }
        } else {
            if (!!errMsg) {
                Toast.fail(errMsg, 0);
            } else {
                Toast.fail(getLabel(501213, "获取CA证书信息失败"), 0);
            }
        }
    }

    onChangeEvt(val) {
        const state = this.state;
        this.setState({...state, certPassword: val});
    }

    renderList() {
        const {isShow, owner, startTime, endTime, signAlg} = this.state;
        const list = [];

        if (isShow == 1) {
            const {requestName, requestMark} = this.state;
            list.push(
                <InputItem
                    value={requestName}
                    editable={false}>
                    {getLabel(1334, "请求标题")}
                </InputItem>
            );

            list.push(
                <InputItem
                    value={requestMark}
                    editable={false}>
                    {getLabel(19502, "流程编号")}
                </InputItem>
            );
        }

        list.push(
            <InputItem
                value={owner}
                editable={false}>
                {getLabel(79, "所有者")}
            </InputItem>
        );

        list.push(
            <InputItem
                value={startTime}
                editable={false}>
                {getLabel(501478, "颁发时间")}
            </InputItem>
        );

        list.push(
            <InputItem
                value={endTime}
                editable={false}>
                {getLabel(501479, "失效时间")}
            </InputItem>
        );

        list.push(
            <InputItem
                value={signAlg}
                editable={false}>
                {getLabel(32344, "加密算法")}
            </InputItem>
        );

        list.push(
            <InputItem
                placeholder={getLabel(501214, "请输入证书密码")}
                type="password"
                onChange={this.onChangeEvt.bind(this)}/>
        );

        return list;
    }

    renderHeader() {
        return <div style={{"text-align": "center"}}> {getLabel(501216, "CA证书验证")}</div>
    }

    renderFooter() {
        return (
            <div style={{"text-align": "center"}}>
                <Flex align="center">
                    <Flex.Item style={{"text-align": "right", "flex": 3}}>
                        <Button
                            type="ghost"
                            inline={true}
                            size="small"
                            onClick={() => this.goback()}
                        >
                            {getLabel(31129, "取消")}
                        </Button>
                    </Flex.Item>
                    <Flex.Item>
                        <div></div>
                    </Flex.Item>
                    <Flex.Item style={{"flex": 3}}>
                        <Button
                            type="primary"
                            inline={true}
                            size="small"
                            onClick={this.doSubmit.bind(this)}
                        >
                            {getLabel(501196, "确定")}
                        </Button>
                    </Flex.Item>
                </Flex>
            </div>
        );
    }

    doSubmit() {
        if (suppoertCAAuth()) {
            const {certPassword, sourcestr} = this.state;
            if (!certPassword) {
                Bubble.error(getLabel(501214, "请输入证书密码"), 2);
            } else {
                checkCAAuth(sourcestr, certPassword, data => this.submitBack(data));
            }
        } else {
            const errorMsg = getLabel(501212, "您当前的客户端不支持CA认证");
            Toast.fail(errorMsg, 2);
        }
    }

    goback() {
        if (window.em && window.em.checkJsApi && window.em.checkJsApi("closeWindow")) {
            window.em.closeWindow();
        } else {
            if (window.opener) {
                try {
                    window.top.close();
                } catch (e) {
                    window.close();
                }
            }
        }
    }


    submitBack(data) {
        const $this = this;
        const {authKey} = this.state;
        if (typeof data == "string") {
            data = JSON.parse(data);
        }
        let signValue = "";
        if (!!data.getSignValue) {
            const result = data.getSignValue;
            if (!!result) {
                signValue = result.signValue;
            }
        }

        if (!signValue) {
            Bubble.error(getLabel(501215, "数据签名失败，未获取到签名后的值"), 2);
        } else {
            saveCAAuthResult({signValue, authKey}).then(response => {
                let success = response.success;
                if (success == 1) {
                    this.goback();
                } else {
                    Bubble.error(getLabel(389490, "认证失败"), 2);
                }
            })
        }
    }


    render() {
        const authData = this.state;
        const {success} = authData;
        if (success == 1) {
            return (
                <List renderFooter={this.renderFooter()}>
                    {this.renderList()}
                </List>
            );
        } else {
            return <div></div>
        }
    }
}